package fun.hijklmn.magic.idGenerator.server.service.impl;

import com.xfvape.uid.utils.DockerUtils;
import com.xfvape.uid.utils.NetUtils;
import com.xfvape.uid.worker.WorkerIdAssigner;
import com.xfvape.uid.worker.WorkerNodeType;
import fun.hijklmn.magic.idGenerator.common.pojo.WorkerNode;
import fun.hijklmn.magic.idGenerator.server.dao.WorkerNodeDao;
import org.apache.commons.lang.math.RandomUtils;

import javax.annotation.Resource;
import java.time.LocalDate;

/**
 * @Description
 * @Author fs
 * @Date 2021/7/12 16:52
 * @Version 0.0.1-SNAPSHOT
 **/
public class DisposableWorkerIdAssigner implements WorkerIdAssigner {

    @Resource
    private WorkerNodeDao workerNodeDao;

    @Override
    public long assignWorkerId() {
        WorkerNode workerNode = buildWorkerNode();
        workerNodeDao.addWorkerNode(workerNode);
        return workerNode.getId();
    }

    private WorkerNode buildWorkerNode() {
        WorkerNode workNode = new WorkerNode();
        if (DockerUtils.isDocker()) {
            workNode.setType(WorkerNodeType.CONTAINER.value());
            workNode.setHostName(DockerUtils.getDockerHost());
            workNode.setPort(DockerUtils.getDockerPort());
            workNode.setLaunchDate(LocalDate.now());
        } else {
            workNode.setType(WorkerNodeType.ACTUAL.value());
            workNode.setHostName(NetUtils.getLocalAddress());
            workNode.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000));
            workNode.setLaunchDate(LocalDate.now());
        }

        return workNode;
    }

}
